package com.doge.walknovel.business.home.genres.genres

import androidx.lifecycle.MutableLiveData
import com.doge.walknovel.api.ApiResultMapTransformer
import com.doge.walknovel.api.ObserverAdapter
import com.doge.walknovel.api.api
import com.doge.walknovel.api.model.StrategyChildInfo
import com.doge.walknovel.api.observeOnMain
import com.doge.walknovel.utils.*
import com.google.gson.reflect.TypeToken

class GenresTabRepository {
    private val folder = "genres"
    private val key = "genresTab"

    val tabs = MutableLiveData<List<StrategyChildInfo>>()

    fun initializeTabs() {
        require(isMainThread())
        runOnIO {
            if (tabs.value == null) {
                val disk: String? = spReadString(key, null, folder)
                val cache: List<StrategyChildInfo>? =
                    fromJson<List<StrategyChildInfo>>(
                        disk,
                        object : TypeToken<List<StrategyChildInfo>>() {}.type
                    )
                if (cache?.isNotEmpty() == true) {
                    runOnUI { cache.also { tabs.value = it } }
                }
            }
            api
                .novelGetGenresTabs()
                .map(ApiResultMapTransformer())
                .observeOnMain()
                .subscribe(object : ObserverAdapter<List<StrategyChildInfo>>() {
                    override fun onNext(t: List<StrategyChildInfo>) {
                        if (tabs.value == null) tabs.value = t
                        runOnIO { spWrite(key, toJson(t), folder) }
                    }

                    override fun onError(e: Throwable) {
                    }
                })
        }

    }
}